import redis
from flask import *
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from .config import app_config_dict
from flask_session import Session
from info.utils.log import *
from info.config import RedisSessionConfig
""" 第一种方法"""
# db = None
# global db
# db = SQLAlchemy(app)
""" 第二种方法 """
# db = SQLAlchemy()
# db = None #type: SQLAlchemy
db:SQLAlchemy = None

# redis_conn = redis.StrictRedis(
#     host=RedisConnConfig.HOST,
#     port=RedisConnConfig.PORT,
#     db=RedisConnConfig.DB,
#     decode_responses=RedisConnConfig.DECODE,
# )

class RedisSession():
    def __init__(self,config = RedisSessionConfig):
        self.config = config
        self.redis_conn = redis.StrictRedis(
            host=self.config.HOST,
            port=self.config.PORT,
            db=self.config.DB,
            decode_responses=self.config.DECODE,
        )

    def set_image_code(self,imageid,image_code):
        self.redis_conn.setex(
            self.config.IMAGE_PREFIX + imageid,
            self.config.IMAGE_CODE_EX,
            image_code
        )
    def get_image_code(self,imageid):
        return self.redis_conn.get(
            self.config.IMAGE_PREFIX + imageid
        )

    def set_tel_code(self,tel,tel_code):
        self.redis_conn.setex(
            self.config.TEL_PREFIX + tel,
            self.config.TEL_CODE_EX,
            tel_code
        )
    def get_tel_code(self,tel):
        return self.redis_conn.get(
            self.config.TEL_PREFIX + tel,
        )

redisSession = RedisSession()

def build_manager(level):
    # 创建app
    app = Flask(__name__)
    # 获得app对应的配置文件，根据开发级别
    app_config = app_config_dict[level]
    # app加载配置文件
    app.config.from_object(app_config)
    # 开启CSRF保护
    CSRFProtect(app)
    # 开启Session代理，写入redis，其配置文件在app_config中
    Session(app)
    # 创建db对象
    global db
    # db.init_app(app)
    db = SQLAlchemy(app)
    # 生成manager
    manager = Manager(app)
    # 数据库迁移配置
    Migrate(app,db)
    manager.add_command('db',MigrateCommand)
    # 开启log的记录
    log_file(app_config.LOGGING_LEVER)

    from info.modules.news import news_blue
    app.register_blueprint(news_blue)

    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

    from info.modules.user import user_blue
    app.register_blueprint(user_blue)

    global redis_conn
    redis_conn = redis.StrictRedis()
    return manager


